﻿using System;
using System.Text;
using System.IO;
using System.Threading;

namespace U9API.APIHelper
{
    public class WriteLog
    {
        static Mutex m_WriteMutex = new Mutex();
        static string Loaclpath = "c:\\debug\\";

        /// <summary>
        /// 记录日志信息
        /// </summary>
        /// <param name="dataText">错误信息</param>
        /// <returns></returns>
        public static bool WriteLine(string dataText)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            bool ret = true;
            m_WriteMutex.WaitOne();

            try
            {
                //string FileName = HttpContext.Current.Request.PhysicalApplicationPath;//这个只在有上下文时候可以用如果程序没有上下文则current为空 例如静态方法
                string FileName = Loaclpath;
                if (FileName[FileName.Length - 1] == '\\')
                {
                    FileName += "Logs\\";
                }
                else
                {
                    FileName += "\\Logs\\";
                }
                //CHECK文件目录存在不  
                if (!Directory.Exists(FileName))
                {
                    Directory.CreateDirectory(FileName);
                }
                FileName += DateTime.Now.ToString("yyyMMdd") + ".log";
                //CHECK文件存在不   
                if (!File.Exists(FileName))
                {
                    FileStream tempfs = File.Create(FileName);
                    tempfs.Close();
                }

                fs = new FileStream(
                    FileName,
                    FileMode.Append,
                    FileAccess.Write,
                    FileShare.None);

                fs.Seek(0, System.IO.SeekOrigin.End);
                sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                string LineText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff ") + dataText;
                sw.WriteLine(LineText);
                sw.WriteLine("==================================================================================");
                if (sw != null)
                {
                    sw.Close();
                    sw = null;
                }

                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
            }
            catch (Exception)
            {
                ret = false;
            }
            finally
            {
                try
                {
                    if (sw != null)
                    {
                        sw.Close();
                        sw = null;
                    }

                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }
                }

                catch
                {

                }
                m_WriteMutex.ReleaseMutex();
            }
            return ret;
        }

        public static bool WriteLine(String className, String methodName, Exception e)
        {
            if (e == null)
            {
                return false;
            }
            FileStream fs = null;
            StreamWriter sw = null;
            bool ret = true;
            m_WriteMutex.WaitOne();

            try
            {
                //string FileName = HttpContext.Current.Request.PhysicalApplicationPath;//这个只在有上下文时候可以用如果程序没有上下文则current为空 例如静态方法
                string FileName = Loaclpath;
                if (FileName[FileName.Length - 1] == '\\')
                {
                    FileName += "Logs\\";
                }
                else
                {
                    FileName += "\\Logs\\";
                }
                //CHECK文件目录存在不  
                if (!Directory.Exists(FileName))
                {
                    Directory.CreateDirectory(FileName);
                }
                FileName += DateTime.Now.ToString("yyyMMdd") + ".log";
                //CHECK文件存在不   
                if (!File.Exists(FileName))
                {
                    FileStream tempfs = File.Create(FileName);
                    tempfs.Close();
                }

                fs = new FileStream(
                    FileName,
                    FileMode.Append,
                    FileAccess.Write,
                    FileShare.None);

                fs.Seek(0, System.IO.SeekOrigin.End);
                sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                StringBuilder data = new StringBuilder();
                data.Append(className);
                data.Append(",");
                data.Append(methodName);
                data.AppendLine(":");
                data.AppendLine(e.Message);
                data.AppendLine(e.StackTrace);
                while (e.InnerException != null)
                {
                    e = e.InnerException;
                    data.AppendLine(e.Message);
                    data.AppendLine(e.StackTrace);
                }
                string LineText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff ") + data.ToString();
                sw.WriteLine(LineText);
                sw.WriteLine("==================================================================================");
                if (sw != null)
                {
                    sw.Close();
                    sw = null;
                }

                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
            }
            catch (Exception)
            {
                ret = false;
            }
            finally
            {
                try
                {
                    if (sw != null)
                    {
                        sw.Close();
                        sw = null;
                    }

                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }
                }

                catch
                {

                }
                m_WriteMutex.ReleaseMutex();
            }
            return ret;
        }

        /// <summary>
        /// 手动添加错误
        /// </summary>
        /// <param name="className"></param>
        /// <param name="methodName"></param>
        /// <param name="errorMgs"></param>
        /// <returns></returns>
        public static bool WriteLine(String className, String methodName, string errorMgs)
        {
            if (errorMgs == null)
            {
                return false;
            }
            FileStream fs = null;
            StreamWriter sw = null;
            bool ret = true;
            m_WriteMutex.WaitOne();

            try
            {
                string FileName = Loaclpath;
                //if (HttpContext.Current != null)
                //{
                //    FileName = "c:\\wms\\";
                //    //HttpContext.Current.Request.PhysicalApplicationPath;//这个只在有上下文时候可以用如果程序没有上下文则current为空 例如静态方法
                //}
                //else
                //{
                //    //FileName = System.Environment.CurrentDirectory;
                //    FileName = "c:\\wms\\";
                //}
                if (FileName[FileName.Length - 1] == '\\')
                {
                    FileName += "Logs\\";
                }
                else
                {
                    FileName += "\\Logs\\";
                }
                //CHECK文件目录存在不  
                if (!Directory.Exists(FileName))
                {
                    Directory.CreateDirectory(FileName);
                }
                FileName += DateTime.Now.ToString("yyyMMdd") + ".log";
                //CHECK文件存在不   
                if (!File.Exists(FileName))
                {
                    FileStream tempfs = File.Create(FileName);
                    tempfs.Close();
                }

                fs = new FileStream(
                    FileName,
                    FileMode.Append,
                    FileAccess.Write,
                    FileShare.None);

                fs.Seek(0, System.IO.SeekOrigin.End);
                sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
                StringBuilder data = new StringBuilder();
                data.Append(className);
                data.Append(",");
                data.Append(methodName);
                data.AppendLine(":");
                data.AppendLine("手动查看日志信息：" + errorMgs);

                string LineText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff ") + data.ToString();
                sw.WriteLine(LineText);
                sw.WriteLine("==================================================================================");
                if (sw != null)
                {
                    sw.Close();
                    sw = null;
                }

                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
            }
            catch (Exception)
            {
                ret = false;
            }
            finally
            {
                try
                {
                    if (sw != null)
                    {
                        sw.Close();
                        sw = null;
                    }

                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }
                }

                catch
                {

                }
                m_WriteMutex.ReleaseMutex();
            }
            return ret;
        }
    }
}
